package com.xxxy.ljh.myapplication.DaoImpl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xxxy.ljh.myapplication.Dao.ClubDao;
import com.xxxy.ljh.myapplication.Dao.UserDao;
import com.xxxy.ljh.myapplication.dphelper.sqliteDBHelper;
import com.xxxy.ljh.myapplication.model.Club;
import com.xxxy.ljh.myapplication.model.User;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 社团数据访问实现类，提供对社团信息的增删改查等数据库操作。
 */
public class ClubDaoImpl implements ClubDao {
    private sqliteDBHelper dbHelper;
    private Context mcontext;

    /**
     * 构造方法，初始化数据库帮助类和上下文环境。
     *
     * @param context 应用程序上下文
     */
    public ClubDaoImpl(Context context) {
        dbHelper = new sqliteDBHelper(context);
        mcontext = context;
    }

    /**
     * 获取所有已审核通过的社团列表。
     *
     * @return 已审核通过的社团列表
     */
    @Override
    public List<Club> getAllClubs() {
        List<Club> clubList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;

        try {
            // 查询已审核通过的社团 (audit_status = 1)
            cursor = db.query("association", null, "audit_status = ?",
                    new String[]{"1"}, null, null, "create_time DESC");

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    Club club = cursorToClub(cursor);
                    clubList.add(club);
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return clubList;
    }

    /**
     * 根据ID获取指定社团的详细信息。
     *
     * @param clubId 社团唯一标识符
     * @return 对应的社团对象，若不存在则返回null
     */
    @Override
    public Club getClubById(int clubId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        Club club = null;

        try {
            cursor = db.query("association", null, "association_id = ?",
                    new String[]{String.valueOf(clubId)}, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                club = cursorToClub(cursor);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return club;
    }

    /**
     * 创建新的社团。
     *
     * @param club 社团信息对象
     * @return 是否创建成功
     */
    @Override
    public boolean createClub(Club club) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long result;

        try {
            ContentValues values = new ContentValues();
            values.put("association_name", club.getAssociation_name());
            values.put("founder_id", club.getFounderId());
            values.put("category", club.getCategory());
            values.put("description", club.getDescription());
            values.put("logo", club.getLogo());
            values.put("contact_phone", club.getContact_phone());
            values.put("contact_email", club.getContact_email());
            values.put("audit_status", club.getAudit_status());
            values.put("status", club.getStatus());
            values.put("member_count", club.getMemberCount());
            values.put("create_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
            values.put("update_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));

            result = db.insert("association", null, values);
        } finally {
            db.close();
        }

        return result != -1;
    }

    /**
     * 更新社团信息。
     *
     * @param club 社团信息对象
     * @return 是否更新成功
     */
    @Override
    public boolean updateClub(Club club) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int result;

        try {
            ContentValues values = new ContentValues();
            values.put("association_name", club.getAssociation_name());
            values.put("category", club.getCategory());
            values.put("description", club.getDescription());
            values.put("logo", club.getLogo());
            values.put("contact_phone", club.getContact_phone());
            values.put("contact_email", club.getContact_email());
            values.put("update_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));

            result = db.update("association", values, "association_id = ?",
                    new String[]{String.valueOf(club.getId())});
        } finally {
            db.close();
        }

        return result > 0;
    }

    /**
     * 删除社团（逻辑删除）。
     *
     * @param clubId 社团唯一标识符
     * @return 是否删除成功
     */
    @Override
    public boolean deleteClub(int clubId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int result;

        try {
            ContentValues values = new ContentValues();
            values.put("status", 0); // 逻辑删除，设置状态为0

            result = db.update("association", values, "association_id = ?",
                    new String[]{String.valueOf(clubId)});
        } finally {
            db.close();
        }

        return result > 0;
    }

    /**
     * 获取所有待审核的社团列表。
     *
     * @return 待审核的社团列表
     */
    @Override
    public List<Club> getPendingClubs() {
        List<Club> clubList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;

        try {
            // 查询待审核的社团 (audit_status = 0)
            cursor = db.query("association", null, "audit_status = ?",
                    new String[]{"0"}, null, null, "create_time DESC");

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    Club club = cursorToClub(cursor);
                    clubList.add(club);
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return clubList;
    }

    /**
     * 审核社团申请。
     *
     * @param clubId    社团ID
     * @param status    审核状态（1通过，2拒绝）
     * @param adminId   审核管理员ID
     * @param remark    审核备注
     * @return 是否审核成功
     */
    @Override
    public boolean auditClub(int clubId, int status, int adminId, String remark) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int result;

        try {
            ContentValues values = new ContentValues();
            values.put("audit_status", status);
            values.put("audit_admin_id", adminId);
            values.put("audit_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
            values.put("audit_remark", remark);

            result = db.update("association", values, "association_id = ?",
                    new String[]{String.valueOf(clubId)});
        } finally {
            db.close();
        }

        return result > 0;
    }

    /**
     * 将Cursor对象转换为Club实体对象。
     *
     * @param cursor 数据库查询结果游标
     * @return 转换后的Club对象
     */
    private Club cursorToClub(Cursor cursor) {
        Club club = new Club();
        club.setId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
        club.setAssociation_name(cursor.getString(cursor.getColumnIndexOrThrow("association_name")));
        club.setFounderId(cursor.getInt(cursor.getColumnIndexOrThrow("founder_id")));
        club.setCategory(cursor.getString(cursor.getColumnIndexOrThrow("category")));
        club.setDescription(cursor.getString(cursor.getColumnIndexOrThrow("description")));
        club.setLogo(cursor.getString(cursor.getColumnIndexOrThrow("logo")));
        club.setContact_phone(cursor.getString(cursor.getColumnIndexOrThrow("contact_phone")));
        club.setContact_email(cursor.getString(cursor.getColumnIndexOrThrow("contact_email")));
        club.setAudit_status(cursor.getInt(cursor.getColumnIndexOrThrow("audit_status")));
        club.setAudit_time(cursor.getString(cursor.getColumnIndexOrThrow("audit_time")));
        club.setAudit_admin_id(cursor.getInt(cursor.getColumnIndexOrThrow("audit_admin_id")));
        club.setAudit_remark(cursor.getString(cursor.getColumnIndexOrThrow("audit_remark")));
        club.setCreate_time(cursor.getString(cursor.getColumnIndexOrThrow("create_time")));
        club.setUpdate_time(cursor.getString(cursor.getColumnIndexOrThrow("update_time")));
        club.setStatus(cursor.getInt(cursor.getColumnIndexOrThrow("status")));
        club.setMemberCount(cursor.getInt(cursor.getColumnIndexOrThrow("member_count")));

        return club;
    }

    /**
     * 检查社团名称是否存在。
     *
     * @param clubName 社团名称
     * @return 是否存在
     */
    public boolean isClubNameExists(String clubName) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        boolean exists = false;

        try {
            cursor = db.query("association", new String[]{"association_id"},
                    "association_name = ?", new String[]{clubName},
                    null, null, null);
            exists = cursor.getCount() > 0;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return exists;
    }
    /**
     * 根据关键字搜索社团
     *
     * @param keyword 搜索关键字
     * @return 匹配的社团列表
     */
    @Override
    public List<Club> searchClubs(String keyword) {
        List<Club> clubList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;

        try {
            // 查询已审核通过的社团 (audit_status = 1)
            String selection = "audit_status = ? AND (association_name LIKE ? OR description LIKE ?)";
            String[] selectionArgs = {"1", "%" + keyword + "%", "%" + keyword + "%"};
            
            cursor = db.query("association", null, selection, selectionArgs, null, null, "create_time DESC");

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    Club club = cursorToClub(cursor);
                    clubList.add(club);
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return clubList;
    }
    
    /**
     * 根据创始人ID获取其创建的社团ID
     * 
     * @param founderId 创始人ID
     * @return 社团ID，如果未找到则返回-1
     */
    @Override
    public int getClubIdByFounderId(int founderId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        int clubId = -1;

        try {
            cursor = db.query("association", new String[]{"association_id"},
                    "founder_id = ?", new String[]{String.valueOf(founderId)},
                    null, null, null);
            
            if (cursor != null && cursor.moveToFirst()) {
                clubId = cursor.getInt(cursor.getColumnIndexOrThrow("association_id"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return clubId;
    }
}